package sys

import (
	"context"
	"fmt"
	"gitee.com/freelifer/module-admin/model"
	"gitee.com/freelifer/module-admin/services/sys"
	"gitee.com/freelifer/module-web-base/request"
	StarterJWT "gitee.com/freelifer/starter-jwt"
	"github.com/go-spring/spring-base/util"
	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
)

var (
	UserVerify = request.Rules{"Username": {request.NotEmpty()}, "Password": {request.NotEmpty()}}
)

func init() {
	// SpringBoot.RegisterBean(new(Service)).AsInterface((*types.FileProvider)(nil))
	gs.Object(new(UserController)).Init(func(c *UserController) {

		gs.PostBinding("/sys/admin/login", c.Login)
		// SpringBoot.GetMapping("/sys/admin/me", c.Me)
		//gs.GetMapping("/sys/admin/me", REST(c.Me))

		///sys/admin/user
		gs.GetMapping("/sys/admin/users", c.GetUsers)
		gs.GetBinding("/sys/admin/user", c.GetUser)
		gs.PostBinding("/sys/admin/user", c.CreateUser)
		//gs.DeleteBinding("/sys/admin/user", c.DeleUser)
	})
}

type UserController struct {
	UserService *sys.UserService       `autowire:""`
	JWTService  *StarterJWT.JWTService `autowire:""`
}

type userBind struct {
	Username string `json:"userName" validate:"required"`
	Password string `json:"password"`
}

// 用户登陆，通过用户名和密码 换取token
func (c *UserController) Login(ctx context.Context, req *userBind) interface{} {
	// err := request.Verify(*req, UserVerify)
	// SpringUtils.Panic(err).When(err != nil)

	u := &model.SysUser{Username: req.Username, Password: req.Password}
	err, user := c.UserService.Login(u)
	util.Panic(err).When(err != nil)
	claims := StarterJWT.JWTClaims{
		UUID: user.UUID,
		ID:   user.ID,
	}
	token, err := c.JWTService.CreateToken(claims)
	util.Panic(err).When(err != nil)
	return token
}

// 用户个人信息
//func (c *UserController) Me(webCtx web.Context, req *userBind) interface{} {
//	token := webCtx.Header("token")
//
//	claims, err := c.JWTService.ParseToken(token)
//	util.Panic(err).When(err != nil)
//	// webCtx.JSON(http.StatusOK, claims)
//	return claims
//}

func (c *UserController) GetUser(ctx context.Context, req *userBind) string {
	return ""
}

func (c *UserController) DeleUser(ctx context.Context, req *userBind) string {
	return ""
}

func (c *UserController) CreateUser(ctx context.Context, req *userBind) string {
	return ""
}

// 用户用户信息
func (c *UserController) GetUsers(webCtx web.Context) {
	var info request.PageInfo
	qString := webCtx.QueryString()
	err := webCtx.Bind(&info)
	if err != nil {
		webCtx.String("参数错误")
		return
	}
	fmt.Printf("PageInfo qString %s\n", qString)
	fmt.Printf("PageInfo %d %d\n", info.Page, info.PageSize)
	_, list, _ := c.UserService.GetUserInfoList(info)

	webCtx.JSON(list)
}
